<?php
/**
 * Created by PhpStorm.
 * User: tom_xia
 * Date: 2018/5/29
 * Time: 19:54
 * 音视频合成
 */
require_once dirname(__DIR__)."/common.php";
use app\cls\tom\Lock;
use app\cls\tom\FFmpeg;
use app\lib\db\DbException;
use app\cls\tom\SysResource;
use app\cls\tom\Process;
use app\cls\tom\Tools;
use app\model\UserMaterial;

$process = new Process(__FILE__);
$process->isTryError =false;
$process->setProcessNum(26);
$process->initProcess();
$redis = SysResource::getRedis();
$db =  SysResource::getDB(true);
$ffmpeg = new FFmpeg();
$jsSDK = new \app\cls\tom\JsSDK(WX_PUBLIC_APP_ID,WX_PUBLIC_APP_SECRECT);
$lock = new Lock("user_material_audio_video_mix");
/*===============
 *初始化模型
 ================*/
$userMaterialModel = new UserMaterial($db);
$cosUploadConfig = \app\cls\tom\Config::load("cos_upload");
while(true){
    try{
        $readyList = $userMaterialModel->getReadyHandleVideoMusic(10);
        echo json_encode($readyList)."\n";
        foreach($readyList as &$info){
            $lockStatus = $lock->tryLock($info["id"]);
            var_dump($lockStatus);
//            $lock->unLock($info["id"]);exit;
            if($lockStatus){
                $mediaId = $info["media_id"];
                $videoUrl = $info["video_url"];
                $musicUrl = $info["music_url"];
                $audioUrl = $info["audio_url"];
                $mediaTransAAC = str_replace(CDN_HOST,CDN_PATH,$audioUrl);
                //2.放大用户声音
                $multiOutputPath = CDN_PATH."/multi_audio/".pathinfo($mediaTransAAC,PATHINFO_BASENAME);
                echo "ori:".$mediaTransAAC."\n";
                echo "mu:".$multiOutputPath."\n";
                $re = $ffmpeg->modifyVolume($mediaTransAAC,$multiOutputPath,10);
                if(!$re){
                    $userMaterialModel->save("update",["mix_status"=>2,"mix_msg"=>$ffmpeg->getLastError(),"mix_count"=>"!mix_count+1"],["id"=>$info["id"]]);
                    $lock->unLock($info["id"]);
                    Tools::writeLog(["msg"=>"音视频混音失败","detail"=>["media_id"=>$mediaId,"msg"=>$ffmpeg->getLastError()],"mix"]);
                    continue;
                }
                $musicPath = $musicUrl ? str_replace(CDN_HOST,CDN_PATH,$musicUrl) : "";
                //3.合成音视频
                $outPutPath = CDN_PATH."/mv/".time()."_".pathinfo($videoUrl,PATHINFO_BASENAME);
                $audioS = $musicPath ? [$musicPath,$multiOutputPath] : [$multiOutputPath];
                $re = $ffmpeg->mixAudioVideo($audioS,str_replace(CDN_HOST,CDN_PATH,$videoUrl),$outPutPath);
                //3.1删除放大/缩小的声音的音频
                if(!filter_var($multiOutputPath,FILTER_VALIDATE_URL)){
                    unlink($multiOutputPath);
                }
                if(!$re){
                    $userMaterialModel->save("update",["mix_status"=>2,"mix_msg"=>$ffmpeg->getLastError(),"mix_count"=>"!mix_count+1"],["id"=>$info["id"]]);
                    $lock->unLock($info["id"]);
                    Tools::writeLog(["msg"=>"音视频混音失败","detail"=>["media_id"=>$mediaId,"msg"=>$ffmpeg->getLastError()],"mix"]);
                    continue;
                }
                //5。保存DB
                $db->reconnect();
                if($re){
                    $userMaterialModel->save("update",["music_video_url"=>str_replace(CDN_PATH,CDN_HOST,$outPutPath),"mix_status"=>1,"mix_count"=>"!mix_count+1"],["id"=>$info["id"]]);
                }else{
                    $userMaterialModel->save("update",["mix_status"=>2,"mix_msg"=>$ffmpeg->getLastError(),"mix_count"=>"!mix_count+1"],["id"=>$info["id"]]);
                }
                $lock->unLock($info["id"]);
            }
        }
        sleep(2);
        $db->reconnect();
    }catch (DBException $e){
        $process->restartProcess();
    }catch (RedisException $e){

    }catch (Exception $e){
        if(!empty($info)){
            $db->update("user_material",["mix_status"=>2,"mix_msg"=>$e->getMessage(),"mix_count"=>"!mix_count+1"],["id"=>$info["id"]]);
            $lock->unLock($info["id"]);
        }
        Tools::writeLog(["msg"=>"音视频混音失败","detail"=>["msg"=>$e->getMessage(),"id"=>isset($info["id"])?$info["id"]:""],"mix"]);
    }
    $process->checkProcessTime(true);
}